<?php

//js для редактирования формы
$this->headScript()->appendFile("/js/admin/form.js");

//подлючение js и css файлов jqGrid и UI
$this->JQueryGrid()->addFiles();

$this->headStyle("#category_dialog * { overflow-x:hidden }");

?>

<script type="text/javascript">

$(document).ready(function() {
	<? if ($this->catalogueCategories) : ?>

	var rows = <?= Zend_Json::encode($this->catalogueCategories, true) ?>;

	<? else : ?>

	var rows = [];

	<? endif ?>

	var formId = "<?= $this->form->getId() ?>";
	var dialogBoxId = "category_dialog";
	var dialogBoxGridId = "category_grid";
	var containerId = "category_list";
    var dialogButtonId = "select_category";

	var dialogBoxGrid = null;

    var multiple = true;

	var dialogBoxGridOptions = {
		datatype: "json",
		colNames: ["Название", "Код", "ID"],
		colModel: [
			{name: "name", index: "name", width: 240},
			{name: "code", index: "code", width: 160},
			{name: "id", index: "id", width: 50}
		],
		mtype: "GET",
		url: "/catalogue/admin/list-category-model-custom",
		rowNum: 500,
		viewrecords: false,
		autowidth: true,
		width:580,
		height:240,
		treeGrid: true,
		treeGridModel: 'adjacency',
        treedatatype: 'json',
        ExpandColumn: 'name',
        ExpandColClick: true
	}

	var elementName = "catalogue[category]";

	function initGrid() {
		if (!dialogBoxGrid) {
			dialogBoxGrid = $("#" + dialogBoxGridId).jqGrid(dialogBoxGridOptions);
		}
		return dialogBoxGrid;
	}

	function addItem(rowId, rowLabel) {
		var name = elementName;
		var id = elementName.replace(/[\]\[]/g, "-").replace(/\-$/, "");

        if (multiple) {
            name += "[" + rowId + "]";
            id += rowId;
        }

		if (!rowLabel) {
			var grid = initGrid();
			var row = grid.jqGrid("getRowData", rowId);
			rowLabel = row["name"];
		}

		var button = $("<span class\"width2\"></span>").button({
			icons: {
				primary: "ui-icon-close"
			},
			text: false
		}).click(function() {
			if (confirm("Удалить привязку к категории?")) {
				$("#" + id).remove();
				$(this).parent().remove();
			}
		});

		var item = $("<li></li>").append("<span>" + rowLabel + "</span>").append("<span>&nbsp;</span>").append(button);

        if (multiple || $("#" + containerId).find("li").length == 0) {
            $("<input type=\"hidden\" id=\"" + id +"\" name=\"" + name + "\" value=\"" + rowId + "\" />").appendTo($("#" + formId));
            item.appendTo($("#" + containerId));
        } else {
            $("#" + formId).find("#" + id).attr("value", rowId);
            $("#" + containerId).find("li").replaceWith(item);
        }

        return true;
	}

    //вешаем dialog
	$("#" + dialogButtonId).find("button").button().click(function() {
		$("#" + dialogBoxId).dialog("open");
	});

    //событие для кнопки добавить/скрыть блок
	$("#" + dialogButtonId).find("[rel=rollup]").toggle(
        function() {
            $(this).addClass("ui-icon-circle-triangle-s").removeClass("ui-icon-circle-triangle-n").attr("title", "развернуть");
            $("#" + dialogButtonId).find(".content").hide(100);
        },
        function() {
            $(this).addClass("ui-icon-circle-triangle-n").removeClass("ui-icon-circle-triangle-s").attr("title", "свернуть");
            $("#" + dialogButtonId).find(".content").show(100);
        }
    );

	$.each(rows, function(i, data) {
		addItem(data[1], data[0]);
	});

	$("#" + dialogBoxId).dialog({
		autoOpen: false,
		height: 400,
		width: 612,
		modal: false,
		title: "Выберите категорию из каталога",

		open: function() {
			initGrid();
		},

		buttons: {
			"Выбрать": function() {
				var rowId = $("#" + dialogBoxGridId).jqGrid("getGridParam", "selrow");
				var result = false;
				if (rowId > 0) {
					result = addItem(rowId);
				}
				if (result) {
					$(this).dialog("close");
				} else {
					$('<span>Выберите конечную категорию</span>').dialog({
						title:'Ошибка',
						buttons:{
							"Ok":function(){
								$(this).dialog("close");
							}
						}
					});
				}
			},

			"Закрыть": function() {
				$(this).dialog("close");
			}
		}
	});
});

</script>

<div id="select_category" class="mb1 zend_form">
	<fieldset>
		<legend>Привязка к модулю "Каталог"</legend>

        <div class="content_right">
            <div class="ui-widget">
                <div class="ui-widget-content ui-corner-all ui-state-default" style="padding:3px">
                    <a class="ui-icon ui-icon-circle-triangle-n" title="Свернуть" rel="rollup" href="javascript:void(null)"></a>
                </div>
            </div>
        </div>

        <div class="content">

            <? if ($this->attachCatalogueCategory) : ?>
            <div id="category_dialog">
                <table id="category_grid"></table>
            </div>
            <div class="ma2">
                <button type="button">Добавить модель</button>
            </div>
            <div class="ma2">
                <ul id="category_list" class="list "></ul>
            </div>
            <? endif ?>

        </div>
	</fieldset>
</div>
